package com.wang.jmonkey.gateway.handler.auth.authentication;

import com.alibaba.fastjson.JSONObject;
import com.wang.jmonkey.common.result.HttpResult;
import org.apache.http.HttpStatus;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @Description 认证失败处理，如token不正确
 * @Author HeJiawang
 * @Date 2021/5/31 16:02
 */
public class AuthenticationFailureHandler  implements ServerAuthenticationFailureHandler {

    @Override
    public Mono<Void> onAuthenticationFailure(WebFilterExchange webFilterExchange, AuthenticationException exception) {
        HttpResult<Void> result = new HttpResult<Void>()
                .setSuccess(false)
                .setCode(HttpStatus.SC_UNAUTHORIZED)
                .setMsg(exception.getMessage());

        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        DataBuffer bodyDataBuffer = response.bufferFactory()
                .wrap(JSONObject.toJSONString(result).getBytes(Charset.defaultCharset()));
        return response.writeWith(Mono.just(bodyDataBuffer))
                .doOnError((error) -> DataBufferUtils.release(bodyDataBuffer));
    }
}
